package spring.library.LibraryProject.config;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import spring.library.LibraryProject.model.response;

/**
 * 异常的统一处理
 * -@RestControllerAdvice这个注解会搜集所有的bean中抛出的异常信息，
 * 并通过 @ExceptionHandler来对这些异常进程处理
 * 在@ExceptionHandler中可以指定异常的类型，这样他就只会处理这种异常
 */
@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {


    //处理所有的异常信息
    @ExceptionHandler
    public response exceptionHandler(Exception e) {
        return new response().fail(e.toString());
    }

    @ExceptionHandler(ArithmeticException.class)
    public response exceptionHandler(ArithmeticException e) {
        System.out.println("ArithmeticException");
        return new response().fail(e.toString());
    }

    @ExceptionHandler(NumberFormatException.class)
    public response exceptionHandler(NumberFormatException e) {
        log.error("logger: 参数:"+e.getMessage()+" 错误:c"+e.toString());
        return new response().fail("参数类型错误");
    }
}
